<template>
  <div class="init-container">
    <div class="gantt-container">
      <div class="query-section">
        <DatePicker
          type="date"
          v-model="selectedDate"
          :options="dateOptions"
          @on-change="handleDateChange"
          placeholder="选择日期"
        />
        <div class="stats-section">
          <div class="stat-item">
            <span class="stat-label">优化时间:</span>
            <span class="stat-value">{{ overlapTime }}小时</span>
          </div>
        </div>
      </div>
      <div class="chart-section" id="ganttChart" ref="chartRef"></div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator';
import * as echarts from 'echarts';
// import { T_cmd, I_cmd } from './command';
// import { N_cGanttChart } from './types';
import {
  Config,
  N_cGanttChart,
  I_cmd,
  T_cmd,
  T_srv,
  Tsrv,
  ifs,
  ts,
  tvs,
  vue
} from './config';

@T_srv.comp
export default class cGanttChart extends vue {
  @Ref() readonly chartRef!: HTMLDivElement;

  private chart: echarts.ECharts | null = null;

  private GT_command: I_cmd = new T_cmd();

  public selectedDate: string = this.GT_command.formatDate(new Date());

  private ganttData: N_cGanttChart.GanttData | null = null;

  public taskData: N_cGanttChart.TaskData[] = [];

  public overlapTime: number = 0;

  private dateOptions = {
    disabledDate(date: Date) {
      return date && date.getTime() > Date.now();
    }
  };

  created() {
    this.GT_command.init(this);
  }

  mounted() {
    this.initChart();
    this.GT_command.getTaskData().then(_ => {
      this.loadData();
    });
  }

  private initChart() {
    this.chart = echarts.init(this.chartRef);
    window.addEventListener('resize', this.handleResize);
  }

  private async loadData() {
    this.ganttData = this.convertTaskDataToGanttData();
    this.calculateOverlapTime();
    this.updateChart();
  }

  private calculateOverlapTime() {
    if (!this.ganttData || this.ganttData.items.length < 2) {
      this.overlapTime = 0;
      return;
    }

    const intervals = this.ganttData.items
      .map(item => ({
        start: item.startTime.getTime(),
        end: item.endTime.getTime()
      }))
      .sort((a, b) => a.start - b.start);

    let totalOverlap = 0;
    let currentEnd = intervals[0].end;

    for (let i = 1; i < intervals.length; i++) {
      if (intervals[i].start < currentEnd) {
        const overlap =
          Math.min(currentEnd, intervals[i].end) - intervals[i].start;
        totalOverlap += overlap;
        currentEnd = Math.max(currentEnd, intervals[i].end);
      } else {
        currentEnd = intervals[i].end;
      }
    }

    this.overlapTime = parseFloat((totalOverlap / 3600000).toFixed(2));
  }

  private convertTaskDataToGanttData(): N_cGanttChart.GanttData {
    return {
      date: this.selectedDate,
      items: this.taskData.map((task, index) => ({
        id: `group-${index + 1}`,
        name: task.hang_group_num,
        startTime: new Date(task.begin_time),
        endTime: new Date(task.end_time),
        process: task.f_name
      }))
    };
  }

  private handleDateChange(date: string) {
    this.selectedDate = date;

    this.GT_command.getTaskData().then(_ => {
      this.loadData();
    });
  }

  private handleResize() {
    this.chart?.resize();
  }

  private updateChart() {
    if (!this.ganttData || !this.chart) return;

    const baseOption = Config.getBaseOption();
    const seriesOption = Config.getSeriesOption(this.ganttData);

    this.chart.setOption(
      {
        ...baseOption,
        yAxis: {
          ...baseOption.yAxis,
          data: this.ganttData.items.map(item => item.name)
        },
        series: [seriesOption]
      },
      {
        notMerge: true
      }
    );
  }

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chart?.dispose();
  }
}
</script>

<style lang="scss" scoped>
.gantt-container {
  display: flex;
  height: 100%;
  padding: 20px;

  .query-section {
    width: 200px;
    padding-right: 20px;
    margin-top: 60px;

    .stats-section {
      margin-top: 20px;
      padding: 10px;
      background: #f5f5f5;
      border-radius: 4px;

      .stat-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;

        .stat-label {
          font-weight: bold;
        }

        .stat-value {
          color: #1890ff;
          font-weight: bold;
        }
      }
    }
  }

  .chart-section {
    flex: 1;
    height: 100%;
  }
}
</style>
